package com.uenpay.im.ui.old.activity.personal;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.callback.OnCommonCallBack;
import com.uenpay.im.entities.PersonInfoConstant;
import com.uenpay.im.invokeitems.person.UpdateInfoInvokItem;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.rx.CommonEvent;
import com.uenpay.util.rx.RxBus;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class EditInfoActivity extends BaseActivity {

    private EditText edit_info_edittext;
    private TextView titleTextView;
    private short update_type = -1;
    private String oldStr = "";
    private View loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_edit_info_layout;
    }

    @Override
    public void initView(View view) {
        initView();
        initListener();
    }

    protected void initView() {
        loading = findViewById(R.id.loading);

        titleTextView = (TextView) findViewById(R.id.title_textview);
        edit_info_edittext = (EditText) findViewById(R.id.edit_info_edittext);
        edit_info_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                edit_info_edittext.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ((TextView) findViewById(R.id.title_right_tv)).setText(R.string.save);
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        update_type = getIntent().getShortExtra("update_type",
                PersonInfoConstant.updateNothing);
        oldStr = getIntent().getStringExtra("oldStr");

        if (update_type == PersonInfoConstant.updateName) {
            edit_info_edittext.setHint(getResources().getString(
                    R.string.input_name));
            titleTextView.setText(getResources().getString(R.string.name));
            edit_info_edittext.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
            edit_info_edittext.setMaxLines(10);
        } else if (update_type == PersonInfoConstant.updateEmail) {
            edit_info_edittext.setHint(getResources().getString(
                    R.string.input_email));
            titleTextView.setText(getResources().getString(R.string.email));
        } else if (update_type == PersonInfoConstant.updateSignature) {
            edit_info_edittext.setHint(getResources().getString(
                    R.string.input_signature));
            titleTextView.setText(getResources().getString(R.string.signature));
            edit_info_edittext
                    .setFilters(new InputFilter[]{new InputFilter.LengthFilter(
                            30)});
        } else if (update_type == PersonInfoConstant.updateAge) {
            edit_info_edittext.setHint(getResources().getString(
                    R.string.input_age));
            edit_info_edittext.setInputType(InputType.TYPE_CLASS_NUMBER);
            titleTextView.setText(getResources().getString(R.string.age));
            edit_info_edittext
                    .setFilters(new InputFilter[]{new InputFilter.LengthFilter(
                            3)});
        }
        if (!TextUtils.isEmpty(oldStr)) {
            edit_info_edittext.setText(oldStr);
            edit_info_edittext.setSelection(oldStr.length());
        }
        Utils.showSoftKeyboard(edit_info_edittext);
    }

    protected void initListener() {
        findViewById(R.id.back_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Utils.hideSoftKeyboard(edit_info_edittext);
                        EditInfoActivity.this.finish();
                    }
                });
        findViewById(R.id.title_right_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // �ж������Ƿ�Ϸ�
                        String content = edit_info_edittext.getText()
                                .toString();
                        if (TextUtils.isEmpty(content)) {
                            IMApplication.showToast(getResources().getString(
                                    R.string.input_text_not_null));
                            return;
                        }
                        if (content.equals(oldStr)) {
                            Utils.hideSoftKeyboard(edit_info_edittext);
                            finish();
                            return;
                        }
                        if (update_type == PersonInfoConstant.updateEmail) {
                            if (!VerificationEmail(content)) {
                                IMApplication.showToast(getResources()
                                        .getString(R.string.email_error));
                            } else {
                                updateInfo("email", content);
                            }
                        } else if (update_type == PersonInfoConstant.updateSignature) {
                            updateInfo("signature", content);
                        } else if (update_type == PersonInfoConstant.updateAge) {
                            updateInfo("age", content);
                        } else {
                            if (update_type == PersonInfoConstant.updateName) {
                                if (content.length() > 10) {
                                    IMApplication.showToast(getResources()
                                            .getString(R.string.name_length));
                                    return;
                                }
                                updateInfo("nickname", content);
                            }
                        }
                    }
                });
    }

    private void updateInfo(String field, final String value) {
        loading.setVisibility(View.VISIBLE);
        UpdatePersonInfoCommonHandle.udpatePersonInfo(field, value,
                new OnCommonCallBack() {

                    @Override
                    public void onSuccess(Object result) {
                        myHandler.sendEmptyMessage(0);
                        UpdateInfoInvokItem.UpdateInfoInvokItemResult results = (UpdateInfoInvokItem.UpdateInfoInvokItemResult) result;
                        if (results != null && results.status == HttpInvokeResultCode.RESULT_OK) {

                            Intent data = new Intent();
                            data.putExtra("result", value);
                            if (update_type == PersonInfoConstant.updateName) {
                                IMApplication.config.setUserName(value);
                            } else if (update_type == PersonInfoConstant.updateSignature) {
                                IMApplication.config.setUserSignature(value);
                            }
                            setResult(RESULT_OK, data);
                            Utils.hideSoftKeyboard(edit_info_edittext);
                            finish();
                        }

                        if (results != null && !TextUtils.isEmpty(results.msg)) {
                            IMApplication.showToast(results.msg);
                        }
                    }

                    @Override
                    public void onFailed(String reason) {
                        myHandler.sendEmptyMessage(0);
                        IMApplication.showToast(reason);
                    }
                });
    }

    private Handler myHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                }
            }
        }

        ;
    };

    /**
     * ��֤����
     */
    private boolean VerificationEmail(String email) {
        Pattern pattern = Pattern
                .compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    @Override
    public void onBackPressed() {
        Utils.hideSoftKeyboard(edit_info_edittext);
        finish();
        super.onBackPressed();
    }
}
